<template>
  <div class="cart-container">
    <!-- 购物车头部 -->
    <div class="cart-header">
      <h1>我的购物车</h1>
      <div class="cart-summary">
        <span>共 {{ totalItems }} 件商品</span>
        <span class="total-price">总计: ¥{{ totalPrice.toFixed(2) }}</span>
      </div>
    </div>

    <!-- 购物车为空状态 -->
    <div v-if="cartItems.length === 0" class="empty-cart">
      <div class="empty-icon">🛒</div>
      <h2>购物车是空的</h2>
      <p>快去挑选心仪的商品吧！</p>
      <NuxtLink to="/catalog" class="continue-shopping">
        继续购物
      </NuxtLink>
    </div>

    <!-- 购物车商品列表 -->
    <div v-else class="cart-content">
      <!-- 商品列表 -->
      <div class="cart-items">
        <div class="cart-item" v-for="item in cartItems" :key="item.id">
          <div class="item-checkbox">
            <input 
              type="checkbox" 
              :checked="item.selected" 
              @change="toggleItemSelection(item.id)"
            >
          </div>
          <div class="item-image">
            <img :src="item.image" :alt="item.name">
          </div>
          <div class="item-info">
            <h3 class="item-name">{{ item.name }}</h3>
            <p class="item-desc">{{ item.description }}</p>
            <div class="item-specs">
              <span class="spec-item">{{ item.color }}</span>
              <span class="spec-item">{{ item.size }}</span>
            </div>
          </div>
          <div class="item-price">
            <span class="current-price">¥{{ item.price.toFixed(2) }}</span>
            <span v-if="item.originalPrice > item.price" class="original-price">
              ¥{{ item.originalPrice.toFixed(2) }}
            </span>
          </div>
          <div class="item-quantity">
            <button 
              class="quantity-btn" 
              @click="decreaseQuantity(item.id)"
              :disabled="item.quantity <= 1"
            >
              -
            </button>
            <input 
              type="number" 
              v-model="item.quantity" 
              @change="updateQuantity(item.id, item.quantity)"
              min="1"
              max="99"
              class="quantity-input"
            >
            <button 
              class="quantity-btn" 
              @click="increaseQuantity(item.id)"
              :disabled="item.quantity >= 99"
            >
              +
            </button>
          </div>
          <div class="item-total">
            ¥{{ (item.price * item.quantity).toFixed(2) }}
          </div>
          <div class="item-actions">
            <button class="remove-btn" @click="removeItem(item.id)">
              删除
            </button>
          </div>
        </div>
      </div>

      <!-- 购物车侧边栏 -->
      <div class="cart-sidebar">
        <div class="order-summary">
          <h3>订单摘要</h3>
          <div class="summary-item">
            <span>商品总价</span>
            <span>¥{{ subtotal.toFixed(2) }}</span>
          </div>
          <div class="summary-item">
            <span>运费</span>
            <span>{{ shipping === 0 ? '免运费' : `¥${shipping.toFixed(2)}` }}</span>
          </div>
          <div class="summary-item discount" v-if="discount > 0">
            <span>优惠折扣</span>
            <span>-¥{{ discount.toFixed(2) }}</span>
          </div>
          <div class="summary-total">
            <span>总计</span>
            <span>¥{{ totalPrice.toFixed(2) }}</span>
          </div>
        </div>

        <div class="coupon-section">
          <h4>优惠券</h4>
          <div class="coupon-input">
            <input 
              type="text" 
              v-model="couponCode" 
              placeholder="请输入优惠券代码"
              @keyup.enter="applyCoupon"
            >
            <button @click="applyCoupon" class="apply-btn">应用</button>
          </div>
          <div v-if="appliedCoupon" class="applied-coupon">
            <span>{{ appliedCoupon.name }}</span>
            <button @click="removeCoupon" class="remove-coupon">×</button>
          </div>
        </div>

        <div class="checkout-section">
          <button 
            class="checkout-btn" 
            @click="checkout"
            :disabled="selectedItems.length === 0"
          >
            结算 ({{ selectedItems.length }} 件商品)
          </button>
          <p class="checkout-note">
            选择商品后才能结算
          </p>
        </div>

        <div class="recommendations">
          <h4>为您推荐</h4>
          <div class="recommendation-items">
            <div 
              class="recommendation-item" 
              v-for="product in recommendations" 
              :key="product.id"
              @click="addToCart(product)"
            >
              <img :src="product.image" :alt="product.name">
              <div class="rec-info">
                <h5>{{ product.name }}</h5>
                <p class="rec-price">¥{{ product.price.toFixed(2) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 购物车数据
const cartItems = ref([
  {
    id: 1,
    name: 'iPhone 15 Pro Max',
    description: '256GB 深空黑色',
    price: 9999.00,
    originalPrice: 10999.00,
    quantity: 1,
    selected: true,
    image: '/banner1.jpg',
    color: '深空黑色',
    size: '256GB'
  },
  {
    id: 2,
    name: 'MacBook Air M2',
    description: '13.6英寸 8GB+256GB',
    price: 7999.00,
    originalPrice: 7999.00,
    quantity: 1,
    selected: true,
    image: '/banner2.jpg',
    color: '深空灰色',
    size: '8GB+256GB'
  },
  {
    id: 3,
    name: 'AirPods Pro',
    description: '主动降噪耳机',
    price: 1899.00,
    originalPrice: 1999.00,
    quantity: 2,
    selected: false,
    image: '/banner3.jpg',
    color: '白色',
    size: '标准版'
  }
])

// 优惠券相关
const couponCode = ref('')
const appliedCoupon = ref(null)

// 推荐商品
const recommendations = ref([
  {
    id: 4,
    name: 'iPad Air',
    price: 4399.00,
    image: '/banner1.jpg'
  },
  {
    id: 5,
    name: 'Apple Watch Series 9',
    price: 2999.00,
    image: '/banner2.jpg'
  },
  {
    id: 6,
    name: 'HomePod mini',
    price: 749.00,
    image: '/banner3.jpg'
  }
])

// 计算属性
const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.selected)
})

const totalItems = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const subtotal = computed(() => {
  return selectedItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

const shipping = computed(() => {
  return subtotal.value >= 99 ? 0 : 10
})

const discount = computed(() => {
  if (!appliedCoupon.value) return 0
  return appliedCoupon.value.type === 'percentage' 
    ? subtotal.value * (appliedCoupon.value.value / 100)
    : appliedCoupon.value.value
})

const totalPrice = computed(() => {
  return subtotal.value + shipping.value - discount.value
})

// 方法
const toggleItemSelection = (itemId) => {
  const item = cartItems.value.find(item => item.id === itemId)
  if (item) {
    item.selected = !item.selected
  }
}

const increaseQuantity = (itemId) => {
  const item = cartItems.value.find(item => item.id === itemId)
  if (item && item.quantity < 99) {
    item.quantity++
  }
}

const decreaseQuantity = (itemId) => {
  const item = cartItems.value.find(item => item.id === itemId)
  if (item && item.quantity > 1) {
    item.quantity--
  }
}

const updateQuantity = (itemId, newQuantity) => {
  const item = cartItems.value.find(item => item.id === itemId)
  if (item) {
    const quantity = parseInt(newQuantity)
    if (quantity >= 1 && quantity <= 99) {
      item.quantity = quantity
    } else {
      item.quantity = 1
    }
  }
}

const removeItem = (itemId) => {
  const index = cartItems.value.findIndex(item => item.id === itemId)
  if (index > -1) {
    cartItems.value.splice(index, 1)
  }
}

const applyCoupon = () => {
  if (!couponCode.value.trim()) return
  
  // 模拟优惠券验证
  const coupons = {
    'SAVE10': { name: '满减券', value: 10, type: 'fixed' },
    'DISCOUNT20': { name: '8折券', value: 20, type: 'percentage' }
  }
  
  const coupon = coupons[couponCode.value.toUpperCase()]
  if (coupon) {
    appliedCoupon.value = coupon
    couponCode.value = ''
  } else {
    alert('优惠券代码无效')
  }
}

const removeCoupon = () => {
  appliedCoupon.value = null
}

const addToCart = (product) => {
  const existingItem = cartItems.value.find(item => item.id === product.id)
  if (existingItem) {
    existingItem.quantity++
  } else {
    cartItems.value.push({
      ...product,
      description: product.description || '',
      originalPrice: product.originalPrice || product.price,
      selected: true,
      color: product.color || '默认',
      size: product.size || '标准'
    })
  }
}

const checkout = () => {
  if (selectedItems.value.length === 0) {
    alert('请选择要结算的商品')
    return
  }
  
  // 这里可以跳转到结算页面
  alert(`准备结算 ${selectedItems.value.length} 件商品，总金额 ¥${totalPrice.value.toFixed(2)}`)
}

// 页面加载时从本地存储恢复购物车数据
onMounted(() => {
  const savedCart = localStorage.getItem('cart')
  if (savedCart) {
    try {
      cartItems.value = JSON.parse(savedCart)
    } catch (e) {
      console.error('Failed to load cart data')
    }
  }
})

// 监听购物车变化，保存到本地存储
watch(cartItems, (newCart) => {
  localStorage.setItem('cart', JSON.stringify(newCart))
}, { deep: true })
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.cart-header h1 {
  margin: 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
}

.cart-summary {
  display: flex;
  gap: 20px;
  align-items: center;
  color: #666;
}

.total-price {
  font-size: 18px;
  font-weight: 600;
  color: #c81623;
}

.empty-cart {
  text-align: center;
  padding: 60px 20px;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
}

.empty-cart h2 {
  color: #333;
  margin-bottom: 10px;
}

.empty-cart p {
  color: #666;
  margin-bottom: 30px;
}

.continue-shopping {
  display: inline-block;
  padding: 12px 30px;
  background-color: #c81623;
  color: white;
  text-decoration: none;
  border-radius: 6px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.continue-shopping:hover {
  background-color: #a0141c;
}

.cart-content {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 30px;
}

.cart-items {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  overflow: hidden;
}

.cart-item {
  display: grid;
  grid-template-columns: 50px 100px 1fr 120px 150px 100px 80px;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  gap: 15px;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-checkbox input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.item-image img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
}

.item-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-name {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.item-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.item-specs {
  display: flex;
  gap: 10px;
}

.spec-item {
  padding: 4px 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 12px;
  color: #666;
}

.item-price {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #c81623;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.item-quantity {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.quantity-btn:hover:not(:disabled) {
  border-color: #c81623;
  color: #c81623;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-input {
  width: 50px;
  height: 32px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.item-total {
  font-size: 16px;
  font-weight: 600;
  color: #c81623;
  text-align: center;
}

.remove-btn {
  padding: 6px 12px;
  background: none;
  border: 1px solid #ddd;
  border-radius: 4px;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.remove-btn:hover {
  border-color: #c81623;
  color: #c81623;
}

.cart-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-summary {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 20px;
}

.order-summary h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
}

.summary-item.discount {
  color: #c81623;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.coupon-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 20px;
}

.coupon-section h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.coupon-input {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.coupon-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.apply-btn {
  padding: 10px 15px;
  background-color: #c81623;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.apply-btn:hover {
  background-color: #a0141c;
}

.applied-coupon {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f0f8ff;
  border-radius: 4px;
  font-size: 14px;
  color: #0066cc;
}

.remove-coupon {
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 16px;
}

.checkout-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 20px;
}

.checkout-btn {
  width: 100%;
  padding: 15px;
  background-color: #c81623;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.2s;
  margin-bottom: 10px;
}

.checkout-btn:hover:not(:disabled) {
  background-color: #a0141c;
}

.checkout-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.checkout-note {
  margin: 0;
  font-size: 12px;
  color: #666;
  text-align: center;
}

.recommendations {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 20px;
}

.recommendations h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #333;
}

.recommendation-items {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.recommendation-item {
  display: flex;
  gap: 12px;
  padding: 10px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.recommendation-item:hover {
  background-color: #f5f5f5;
}

.recommendation-item img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.rec-info h5 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #333;
}

.rec-price {
  margin: 0;
  font-size: 14px;
  color: #c81623;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cart-content {
    grid-template-columns: 1fr;
  }
  
  .cart-item {
    grid-template-columns: 1fr;
    gap: 10px;
    text-align: center;
  }
  
  .item-image img {
    width: 100px;
    height: 100px;
  }
  
  .item-quantity {
    justify-content: center;
  }
  
  .cart-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>